package edu.ynu.se.xiecheng.achitectureclass.common.controller;

import edu.ynu.se.xiecheng.achitectureclass.common.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.common.repository.UserRepository;
import edu.ynu.se.xiecheng.achitectureclass.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;

    // 用户注册接口
    @PostMapping("/register")
    public ResponseEntity<String> registerUser(@RequestParam String u_id, @RequestParam String u_password) {
        String result = userService.registerUser(u_id, u_password);
        if ("注册成功".equals(result)) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    // 用户登录接口
    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> loginUser(@RequestParam String u_id, @RequestParam String u_password) {
        Map<String, Object> response = new HashMap<>();
        User user = userRepository.findByUId(u_id);

        if (user == null) {
            response.put("message", "用户不存在");
            return response;  // 返回 JSON 格式的错误信息
        }

        if (user.getuPassword().equals(u_password)) {
            String accessToken = userService.getFBoxAccessToken();
            String cloudToken = userService.getYSCloudAccessToken();

            if (accessToken != null) {
                user.setAccessToken(accessToken);
                userRepository.save(user);
            }

            if (cloudToken != null) {
                user.setCloudToken(cloudToken);
                userRepository.save(user);
            }

            response.put("message", "登录成功");
            response.put("u_id", user.getuId());
            response.put("access_token", accessToken);
            response.put("cloud_token", cloudToken);
            return response;  // 返回 JSON 格式的成功信息
        } else {
            response.put("message", "密码错误");
            return response;  // 返回 JSON 格式的密码错误信息
        }
    }
}
